{% extends "two_columns.html" %}

{% block title %} Experiment Participation {% endblock %}

{% block head %}
  {{ super() }}

  <script language="javascript" type="text/javascript">
    function submitReview() {
      var keys = [
        {% for treatment in treatments %}
          '{{ treatment.key() }}',
        {% endfor %}
      ]

      // Go through the rank divs to find which treatments are in them
      var container = document.getElementById('container');
      var ranking = '';
      var num_ranked = 0;
      for (var i = 0; i < container.children.length; i++) {
        var rank = container.children[i];
        var ties = '';
        for (var j = 0; j < rank.children.length; j++) {
          var treatment_num = rank.children[j].innerHTML.replace(/[^0-9]/g, '');
          if (!treatment_num)
            continue;
          ties = ties + keys[treatment_num] + '=';
          num_ranked = num_ranked + 1;
        }
        if (ties != '')
          ranking = ranking + ties.slice(0, -1) + '>';
      }

      // Grab their feedback if they left any
      var feedback_box = document.getElementById('feedback');
      var feedback = encodeURIComponent(feedback_box.value);

      // Make sure that all of the treatments got ranked
      if (num_ranked != keys.length) {
        alert('Please rank all of the treatments to continue.');
        return;
      }

      // Build up a submit url and redirect to it
      var submit_url = '/submit?exp_key={{ experiment.key() }}'
      submit_url = submit_url + '&ranking=' + ranking.slice(0, -1);
      submit_url = submit_url + '&feedback=' + feedback;
      window.location = submit_url;
    }

    function allowDrop(ev) {
      ev.preventDefault();
    }

    function drag(ev) {
      ev.dataTransfer.setData('source_id', ev.target.id);
    }

    function drop(ev) {
      ev.preventDefault();
      var target_id = ev.target.id;
      // Confirm that you're not adding it to another rankable object
      if (ev.target.className.indexOf('rankable') !== -1)
        target_id = ev.target.parentNode.id;

      // Get the actual Elements for the source and target
      var source_id = ev.dataTransfer.getData('source_id');
      var source = document.getElementById(source_id);
      var target = document.getElementById(target_id);
      target.appendChild(source);
      unhighlight(target);

      // Add new empty ranks on either side
      var container = target.parentNode;
      var newRankBefore = target.cloneNode();
      var newRankAfter = target.cloneNode();
      newRankBefore.id = newRankBefore.id + 'b';
      newRankAfter.id = newRankAfter.id + 'a';
      container.insertBefore(newRankBefore, target);
      container.insertBefore(newRankAfter, target.nextSibling);

      // Preform cleanup and cosmetic changes
      removeExtraRanks(container);
      adjustSizes(container);
      removeUnneededStartingBox();
    }

    function removeUnneededStartingBox() {
        // Check if there are any rankable objects remaining in the starting box
        // If they've all been moved elsewhere, get rid of the arrow and box
        var box = document.getElementById('starting_box');
        if (box) {
            var num_remaining = box.innerHTML.search('rankable');
            if (num_remaining <= 0) {
                box.parentNode.removeChild(box);
                var arrow = document.getElementById('arrow');
                arrow.parentNode.removeChild(arrow);
            }
        }
    }

    function removeExtraRanks(container) {
      // Flatten any adjacent empty ranks into a single empty rank
      for (var i = 0; i < container.children.length; i++) {
        child = container.children[i];
        if (child.children.length)
          continue;
        nextChild = container.children[i + 1];
        while (nextChild && !nextChild.children.length) {
          container.removeChild(nextChild);
          nextChild = container.children[i + 1];
        }
      }
    }

    function adjustSizes(container) {
      // Make the first and last ranks larger than the others
      var numChildren = container.children.length;
      for (var i = 0; i < numChildren; i++) {
        child = container.children[i];
        if (!child || !child.className)
          continue;
        child.className = child.className.replace(/end/, '');
        if (i == 0 || i == numChildren - 1) {
          child.className = child.className + ' end';
        }
      }
    }

    function highlight(rank) {
      rank.className = rank.className + ' highlighted';
    }

    function unhighlight(rank) {
      rank.className = rank.className.replace(/highlighted/, ' ');
    }

    function update_characters_remaining() {
      var remaining_field = document.getElementById('remaining_characters');
      var feedback_field = document.getElementById('feedback');
      var MAX_LEN = 800;

      if (feedback_field.value.length > MAX_LEN)
        feedback_field.value = feedback_field.value.substring(0, MAX_LEN);
      else
        remaining_field.innerHTML = 'Characters remaining: ' +
                                    (MAX_LEN - feedback_field.value.length) +
                                    '/' + MAX_LEN;
    }
  </script>
{% endblock %}

{% block first_column %}
  <h1> {{ experiment.name }}: Participate </h1>

  <div class="warning">
    This experiment is for <font class="giant">{{ experiment.device }}</font>
    <u>only</u>!  If you are not currently on a <font class="giant">
    {{ experiment.device }}</font> please do not participate.
  </div>

  {% if experiment.experiment_type == "chrome-gestures" %}
    <p>
      To try out this experiment, simply Copy/Paste the following cryptic url
      into your address bar.
    </p>

    <div class="command rectangle">
      chrome://salsa/#
      {{- experiment|encode_experiment(treatments, properties) }}
    </div>
  {% else %}
    <p>
      To try out this experiment, simply press Ctrl + Alt + t to open a terminal
      and paste in the cryptic command below.  (Note that to paste into the
      terminal you must either right click and press paste or use Ctrl + Shift
      + v on your keyboard)
    </p>

    <div class="command rectangle">
      try_touch_experiment
      {{ experiment|encode_experiment(treatments, properties) }}
    </div>
  {% endif %}

  <p>
    This will allow you to switch between the treatments and see which you
    prefer. Try them each out by following the experiment-specific
    instructions below.  Once you have tried all of the treatments, use the
    form on the right to rank your experiences.
  </p>

  <p class="rectangle"> {{ experiment.instructions|safe }} </p>

  <p class="comment">
    Created {{ experiment.created }} by
    <a href="mailto:{{ experiment.owner }}@google.com?cc=chromeos-tango@google.com">
      {{ experiment.owner }}
    </a>
  </p>


{% endblock %}

{% block second_column %}
  <h1> Rate your experiences </h1>

  {% if user|string in experiment.participants %}
    <div class="error">
      <b>Error!</b> You have already completed this experiment. Subsequent
      submissions will <b>overwrite</b> your previous rankings!
    </div>
    <script type="text/javascript">
        window.onload = function(){ alert('Error! you have already ' +
                                          'completed this experiment!'); }
    </script>
  {% endif %}

  {% if treatments|length > 2 %}
    <p>
      Drag the following blocks into the gray rectangle to sort the treatments
      you just experienced from best to worst.
    </p>
    <p>
      The better a treatment is, the higher it should be placed.  If two
      treatments were the same, you may place them next to each other.  Don't
      be shy if you couldn't decide between two of them.  Ties provide valuable
      information as well.
    </p>

    <center>
    <table><tr>
      <td>
        <table id="starting_box">
        {% for treatment in treatments %}
          <tr><td>
          <div class="rankable" id="test{{ loop.index0 }}" draggable="true"
               ondragstart="drag(event)">
            Treatment {{ loop.index0 }}
          </div>
          </td></tr>
        {% endfor %}
        </table>
      </td>
      <td id="arrow">
         <div class="arrowbody"></div>
         <div class="arrowhead"></div>
      </td>
      <td>
        <table>
          <tr><th>&uarr; Better &uarr;</th></tr>
          <tr><td>
            <div id="container" class="rank_container">
              <div id="rank1" ondragover="allowDrop(event)" ondrop="drop(event)"
                   ondragenter="highlight(this)" ondragleave="unhighlight(this)"
                   class="rank end"></div>
            </div>
          </td></tr>
          <tr><th>&darr; Worse &darr;</th></tr>
        </table>
      </td>
    </tr></table>
    </center>
  {% else %}
    <form action="submit" method="get">
    <input type="hidden" name="exp_key" value="{{ experiment.key() }}">
    <p>
    <input type="radio" name="ranking"
      value="{{ treatments[0].key() }}>{{ treatments[1].key() }}">
      Treatment 0 is better
    <br>
    <input type="radio" name="ranking"
      value="{{ treatments[0].key() }}={{ treatments[1].key() }}">
      They are the same
    <br>
    <input type="radio" name="ranking"
      value="{{ treatments[1].key() }}>{{ treatments[0].key() }}">
      Treatment 1 is better
    </p>
  {% endif %}

  <p>
    (Optional) If you have any comments you would like to include you may do
    so below.
  </p>
  <p>
    <textarea rows="3" cols="40" id="feedback" name="feedback"
              onKeyUp="update_characters_remaining()"
              onKeyDown="update_characters_remaining()"></textarea>
    <div id="remaining_characters"></div>
  </p>

  {% if treatments|length > 2 %}
    <p><button name="submit" onclick="submitReview()">Submit</button></p>
  {% else %}
    <p><input type="submit"></p>
    </form>
  {% endif %}

{% endblock %}
